package cn.com.digitalnet.ad.web;

import java.io.IOException;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.shiro.authz.annotation.RequiresRoles;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import cn.com.digitalnet.ad.service.CodeService;

import com.google.common.collect.Maps;

import freemarker.template.Configuration;
import freemarker.template.Template;

/**
 * 代码生成，目前只生成了mybatis的xml文件
 * @author qidafang
 */
@RequiresRoles("Admin")
@Controller
@RequestMapping(value = "/code")
public class CodeController{
	
	@Autowired CodeService service;
	private static final String DEFAULT_ENCODING = "utf-8";
	private Template template;
	private Configuration configuration;
	

	
	@RequestMapping(method = RequestMethod.GET)
	public String form() {
		return "codeForm";
	}

	@RequestMapping(value = "code")
	public String code(@RequestParam("className") String className, 
			@RequestParam("path") String path, 
			@RequestParam("tableName") String tableName, 
			HttpServletRequest request, 
			Model model) throws Exception{
		
		Map<String,Object> context = Maps.newHashMap();
		context.put("className", className);
		context.put("path", path);
		context.put("tableName", tableName);
		
		service.code(request,template,configuration,context,model);
		
		return "codeCode";
	}
	
	@RequestMapping(value="table")
	public String table(){
		
		return "codeTable";
	}
	
	@RequestMapping("create")
	public String create(@RequestParam("className") String className, 
			@RequestParam("path") String path, 
			@RequestParam("tableName") String tableName, 
			Model model) throws Exception{
		
		Map<String,Object> context = Maps.newHashMap();
		
		context.put("className", className);
		context.put("path", path);
		context.put("tableName", tableName);
		//返回的list
		context.put("list",className.toLowerCase()+"s");
		context.put("english",className.toLowerCase());
		
		service.code(null,template,configuration,context,model);
		return "codeCode";
	}
	
	/**
	 * 注入Freemarker引擎配置,构造Freemarker 邮件内容模板.
	 */
	@Autowired
	public void setFreemarkerConfiguration(Configuration freemarkerConfiguration) throws IOException {
		configuration = freemarkerConfiguration;
		// 根据freemarkerConfiguration的templateLoaderPath载入文件.
		template = configuration.getTemplate("mybatis_xml.ftl", DEFAULT_ENCODING);
	}
}
